package dup.login.demo.config;

import dup.login.demo.util.JBCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {
    private AuthDetailsService authDetailsService;

    @Autowired
    public void setUserDetailsService(AuthDetailsService authDetailsService) {
        this.authDetailsService = authDetailsService;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/vender/**", "/assets/**", "/test", "/test/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //.csrf().disable()
                .formLogin().loginPage("/login")
                //.defaultSuccessUrl("/user/index")
                .and()
                .rememberMe().rememberMeParameter("remember")
                .and()
                .logout().logoutUrl("/user/logout").logoutSuccessUrl("/user/login")
                .and()
                .authorizeRequests()
                .antMatchers("/login", "/user/logout").permitAll()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/user/**").hasAuthority("USER");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(authDetailsService);
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new JBCryptPasswordEncoder();
    }

}
